package com.entrogy.controller;

import com.entrogy.bean.*;
import com.entrogy.config.Result;
import com.entrogy.service.ClassService;
import com.entrogy.service.CourseService;
import com.entrogy.utils.ApiReturnUtil;
import com.entrogy.utils.StrUtils;
import com.entrogy.utils.constants.ErrorEnum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author xlr
 * @date 2019-06-04
 */
@RestController
@Api(description = "对课程的相关操作接口")
@RequestMapping(value = "/course")
public class CourseController {

    @Autowired
	private CourseService courseService;//课程管理service接口

    @Autowired
	private ClassService classService;// 班级管理service接口

    @ApiOperation(value = "新增学校的静态课程（每个学校都不一样，一个学校一种课程设计的科目）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "courseName",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "uid",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "schoolCode",paramType = "query",dataType = "int",required = true)
    })
	@RequiresPermissions("static_course:add")
	@RequestMapping(value = "/insertstaticcourse",method = RequestMethod.POST)
    public Map<String,Object> insertStaticCourse(String courseName,String uid,String schoolCode){
		List<String> list=courseService.getStaticCourseName(schoolCode);
		if (list.contains(courseName)){
			return ApiReturnUtil.error("该课程已经存在,请重新添加");
		}else{
			int code = courseService.insertStaticCourse(courseName,uid,schoolCode);
			if(code == 1){
				return ApiReturnUtil.success("添加成功","");
			}
			return ApiReturnUtil.error("添加失败");
		}

    }
    @ApiOperation(value = "更新学校的静态课程/静态课程只能更新不能删除。。。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",paramType = "query",dataType = "int",required = true),
			@ApiImplicitParam(name = "courseName",paramType = "query",dataType = "String",required = true),
			@ApiImplicitParam(name = "uid",paramType = "query",dataType = "String",required = true),
            @ApiImplicitParam(name = "schoolCode",paramType = "query",dataType = "int",required = true)
    })
	@RequestMapping(value = "updatestaticcourse",method = RequestMethod.POST)
	@RequiresPermissions("static_course:update")
    public Map<String,Object> updateStaticCourse(int id,String courseName,String uid,String schoolCode){
		List<String> list=courseService.getStaticCourseName(schoolCode);
		if (list.contains(courseName)) {
			return ApiReturnUtil.error("该课程已经存在,请重新添加");
		}else{
			int code = courseService.updateStaticCourse(id,courseName,uid,schoolCode);
			if(code == 1){
				return ApiReturnUtil.success("更新成功","");
			}
			return ApiReturnUtil.error("更新失败");
		}
    }

    @ApiOperation(value = "获取该学校的静态课程列表")
    @RequestMapping(value = "/getstaticcourse",method = RequestMethod.GET)
//	@RequiresPermissions("static_course:list")
    public Map<String,Object> getStaticCourse(String schoolCode){
       List<StaticCourseEntity> lists = courseService.getStaticCourse(schoolCode);
		return ApiReturnUtil.success("获取成功",lists);
	}

    @ApiOperation(value = "新增课程（班级名称+课程名称 例如 初二1班语文）")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "courseName", paramType = "query", dataType = "String", required = true),
			@ApiImplicitParam(name = "classId", paramType = "query", dataType = "Integer", required = true),
			@ApiImplicitParam(name = "staticCourseId", paramType = "query", dataType = "Integer", required = true),
			@ApiImplicitParam(name = "courseTotalScore", paramType = "query", dataType = "Double", value = "科目总分")
	})
	@RequestMapping(value = "/insertcourse",method = RequestMethod.POST)
    public Map<String,Object> insertCourse(Integer classId, String schoolCode, Integer staticCourseId, Double courseTotalScore){
    	// 限制科目总分
    	if (courseTotalScore != null){
    		if (courseTotalScore <= 0 || courseTotalScore >= 200){
    			return ApiReturnUtil.error("对不起，新增失败，科目总分必须在0-200分之间！");
			}
		}
    	int courseId = 0;
    	String classIds = classId.toString();
    	ClassEntity classEntity = classService.getClassById(classId,Integer.parseInt(schoolCode));
		String  courseName = classEntity.getClassName().concat(courseService.getCourseNameById(schoolCode,staticCourseId));
    	if(staticCourseId <= 9 && staticCourseId!=null){
    		courseId = Integer.parseInt(classIds.substring(0,classIds.length()-1).concat(staticCourseId.toString()));
		}else{
			courseId = Integer.parseInt(classIds.substring(0,classIds.length()-2).concat(staticCourseId.toString()));
		}
		List<Integer>  list = courseService.getIdBySchoolCode(schoolCode);
		if (list.contains(courseId)) {
			return ApiReturnUtil.error("该班级课程已经分配！");
		}else{
			Integer gradeId = classEntity.getParentId();
			int code = courseService.addCourse(courseName, classId, schoolCode, courseId, staticCourseId, gradeId, courseTotalScore);
			if(code == 1){
				return ApiReturnUtil.success("新增成功","");
			}
			return ApiReturnUtil.error("新增失败");
		}
	}

	@ApiOperation(value = "删除课程")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id",paramType = "query",dataType = "int",required = true)
	})
	@RequiresPermissions("course:delete")
	@RequestMapping(value = "/deletecourse",method = RequestMethod.DELETE)
	public Map<String,Object> deleteCourse(int id,String schoolCode){
    	int code = courseService.deleteCourse(id,schoolCode);
		if(code == 1){
			return ApiReturnUtil.success("删除成功","");
		}
		return ApiReturnUtil.error("删除失败");
	}


	@ApiOperation(value = "修改课程")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id",paramType = "query",dataType = "int",required = true),
			@ApiImplicitParam(name = "courseName",paramType = "query",dataType = "String",required = true),
	})
	@RequiresPermissions("course:update")
	@RequestMapping(value = "/updatecourse",method = RequestMethod.POST)
	public Map<String,Object> updateCourse(Integer id,Integer classId,String schoolCode,Integer courseId){
		ClassEntity classEntity=classService.getClassById(classId,Integer.parseInt(schoolCode));
		String  tid=classId.toString().substring(0,5).concat(courseId.toString());
		String  courseName=classEntity.getClassName().concat(courseService.getCourseNameById(schoolCode,courseId));
		List<Integer>  list=courseService.getIdBySchoolCode(schoolCode);
		if (list.contains(Integer.parseInt(tid ))) {
			return ApiReturnUtil.error("该班级课程已经分配！");
		}else{
			int code = courseService.updateCourse(id,courseName,tid);
			if(code == 1){
				return ApiReturnUtil.success("修改成功","");
			}
			return ApiReturnUtil.error("修改失败");
		}

	}


	@ApiOperation(value = "课程列表")
	@ApiImplicitParams({
		    @ApiImplicitParam(name = "courseName",paramType = "query",dataType = "String",required = false),
			@ApiImplicitParam(name = "gradeId",paramType = "query",dataType = "String",required = false),
			@ApiImplicitParam(name = "classId",paramType = "query",dataType = "String",required = false),
			@ApiImplicitParam(name = "page",paramType = "query",dataType = "int",required = false),
			@ApiImplicitParam(name = "total",paramType = "query",dataType = "int",required = false)
	})
	@RequestMapping(value = "/getcourselist",method = RequestMethod.POST)
//	@RequiresPermissions("course:list")
	public PageBean<CourseEntity> getCourseList(String courseName,String gradeId,String classId,int page,int total,String schoolCode){
    	if (!StrUtils.isNullOrEmpty(courseName)){
    		courseName = courseName;
		}
    	if (!StrUtils.isNullOrEmpty(gradeId) ){
			gradeId = gradeId.substring(0,3); //截取前三位 代表年级
		}
		if (!StrUtils.isNullOrEmpty(classId)){
			classId = classId;
		}
		int totalDB = courseService.getTotal(courseName,gradeId,classId,schoolCode);
		PageHelper.startPage(page,total);
       	List<CourseEntity>  list = courseService.getCourseList(courseName,gradeId,classId,schoolCode);
		return new PageBean<CourseEntity>().pageBeans(list,totalDB);
	}

	/**
	 *    获取学生
	 * @param schoolCode
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@ApiOperation(value = " 获取学生列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "schoolCode",paramType = "query",dataType = "String",required = false),
			@ApiImplicitParam(name = "currentPage",paramType = "query",dataType = "int",required = false),
			@ApiImplicitParam(name = "pageSize",paramType = "query",dataType = "int",required = false),
			@ApiImplicitParam(name = "name",paramType = "query",dataType = "String",required = false)
	})
    @GetMapping(value="/getUserList")
    public Result<PageBean> getUserList(String schoolCode, int currentPage, int pageSize,String name){
		int totals = courseService.getUserListTotal(schoolCode,name);
		PageHelper.startPage(currentPage,pageSize);
		List<Map<String,Object>>  list = courseService.getUserList(schoolCode,name);
		return new Result<PageBean>().getResult(401,"查询成功",1,new PageBean<Map<String,Object>>().pageBeans(list,totals));
	}


	/**
	 *  分配
	 * @return
	 */
	/*@ApiOperation(value = " 分配")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "courseId",paramType = "query",dataType = "String[]",required = false),
			@ApiImplicitParam(name = "schoolCode",paramType = "query",dataType = "String",required = false),
			@ApiImplicitParam(name = "teacherId",paramType = "query",dataType = "int",required = false)
	})
	@PostMapping("/distribute")
	public Result  distribute(String  teacherId,String[] courseId,String schoolCode){
		int code=courseService.accountAssignment(courseId,teacherId,schoolCode);
		if (code==1){
			return new Result<PageBean>().getResult(401,"分配成功",1,"");
		}
		    return new Result<PageBean>().getResult(402,"分配失败",2,"");
	}*/
	@ApiOperation(value = "清除课程")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "schoolCode",paramType = "query",dataType = "String",required = false),
			@ApiImplicitParam(name = "teacherId",paramType = "query",dataType = "int",required = false)
	})
	@GetMapping(value="/clearCourse")
	public Map<String,Object>  clearCourse(String teacherId,String schoolCode){
		int code=courseService.clearCourse(teacherId,schoolCode);
		if(code==1) {
			return  ApiReturnUtil.success("清除成功","");
		}
			return  ApiReturnUtil.error("清除失败");
	}


	@ApiOperation(value = "根据年级查询出所有课程列表用于创建考试，由于文理分科，一个年级的科目可能不同，该接口已弃用")// 由于文理分科，该接口已弃用
	@ApiImplicitParams({
			@ApiImplicitParam(name = "gradeId",paramType = "query",dataType = "String",required = false),
			@ApiImplicitParam(name = "schoolCode",paramType = "query",dataType = "String",required = false)
	})
	@RequestMapping(value = "/getCourseListByGradeId",method = RequestMethod.POST)
	public Msg getCourseListByGradeId(String gradeId, Integer schoolCode) {
		List<StaticCourseEntity> staticCourseList = courseService.getCourseListByGradeId(gradeId, schoolCode);
		//需要验证是否一个年级的所有的课程是否已经分配完毕，没有分配完毕不能创建考试，TODO 暂时默认一个年级的所有科目均相同
		boolean isFinishAssignCourse = courseService.hasFinishAssignCourse(gradeId, staticCourseList, schoolCode);
		if (!isFinishAssignCourse){
			return Msg.fail(ErrorEnum.E_101, "该年级的班级拥有的课程不一致，请到课程管理中为该年级的所有班级分配一致的课程再创建考试！");
		}
		return Msg.success().add("list", staticCourseList);
	}

	@ApiOperation(value = "查询该学校的所有静态科目")
	@GetMapping(value = "/listStaticCourse")
	public Msg listStaticCourse() {
		Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
		List<StaticCourseEntity> staticCourseList = courseService.listStaticCourse(schoolCode);
		return Msg.success().add("list", staticCourseList);
	}


}
